/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable no-restricted-globals */
import React from 'react';
import { Table, InputNumber, Form } from 'antd';
import { brandsMap_name } from '@/utils/utils';
import './ServiceFeeTable.less';

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  limitDecimals = value => {
    // eslint-disable-next-line no-useless-escape
    const reg = /^(\-)*(\d+)\.(\d\d).*$/;
    if (typeof value === 'string') {
      return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : '';
    }
    if (typeof value === 'number') {
      return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : '';
    }
    return '';
  };

  toggleEdit = () => {
    // eslint-disable-next-line react/no-access-state-in-setstate
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            { required: true, message: '请输入价格！' },
            {
              pattern: /^(([0-9](\.\d{1,2})?)|10|10.0)$/,
              message: '请输入正确的格式，价格不超过10元，最多保留两位小数！',
            },
          ],
          initialValue: record[dataIndex],
        })(
          <InputNumber
            ref={node => {
              this.input = node;
            }}
            onPressEnter={this.save}
            onBlur={this.save}
            min={0}
            step={0.01}
            formatter={this.limitDecimals}
            parser={this.limitDecimals}
            style={{ width: '100%' }}
            placeholder="请输入保管费"
          />,
        )}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class ServiceFeeTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '品牌',
        dataIndex: 'brand',
        width: '50%',
        render: (brand, record) => {
          return brandsMap_name(brand) === 'undefined' ? record.brand_cn : brandsMap_name(brand);
        },
      },
      {
        title: '入库保管费',
        dataIndex: 'fee',
        editable: true,
        width: '50%',
      },
    ];

    this.state = {
      dataSource: [],
    };
  }

  componentDidMount() {
    const { value = [] } = this.props;
    this.setState({
      dataSource: value,
    });
  }

  handleSave = row => {
    const { onChange } = this.props;
    const { dataSource } = this.state;
    const newData = [...dataSource];
    const index = newData.findIndex(item => row.brand === item.brand);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData }, () => {
      onChange && onChange(this.state.dataSource);
    });
  };

  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Table
        style={{ width: '100%' }}
        rowKey="brand"
        components={components}
        rowClassName={() => 'editable-row'}
        bordered
        dataSource={dataSource}
        columns={columns}
        pagination={false}
      />
    );
  }
}

export default ServiceFeeTable;
